import * as THREE from "../build/three.module.js";
import { CSS3DObject,CSS3DRenderer,CSS3DSprite } from "./jsm/renderers/CSS3DRenderer.js";

function makeElementObject(type, width, height,scale) {
    const obj = new THREE.Object3D

    const element = document.createElement( type );
    element.style.width = width+'px';
    element.style.height = height+'px';
    element.style.opacity = 0.99;
    //element.style.boxSizing = 'border-box'

    var css3dObject = new CSS3DSprite( element );
	css3dObject.scale.set(scale,scale,scale);
    obj.css3dObject = css3dObject
    obj.add(css3dObject)

    // make an invisible plane for the DOM element to chop
    // clip a WebGL geometry with it.
    var material = new THREE.MeshPhongMaterial({
        opacity	: 0.0,//不显示mesh
        color	: new THREE.Color( 0xFFFFFF ),
        transparent:true,//div透明
        blending: THREE.MultiplylBlending,
    });
    var geometry = new THREE.BoxGeometry( width, height, 1 );
    var mesh = new THREE.Mesh( geometry, material );
    mesh.castShadow = true;
    mesh.receiveShadow = true;
	mesh.ignoreSelect = true;
    obj.lightShadowMesh = mesh
    obj.add( mesh );

    return obj
}

//记录所有标签元素
var allCss3DObjects = [];
//设置单个元素显示状态
function setLabelVisible(label,visible){
	label.visible = visible;
	label.children[0].css3dObject.visible = visible;
}
//显示这个标签show=false的标签
function setShowFalseLabelVisible(label,visible){
	if(!label.defaultVisible){
		label.visible = visible;
		label.children[0].css3dObject.visible = visible;
	}
}

//组合：设置给定tag的标签可见性
function setVisibilityByTag(tag,visible){
	for(let label of allCss3DObjects){
		if(label.tag == tag){
			setLabelVisible(label,visible);
		}
	}
}

//设置全部元素显示状态
function setAllLabelVisible(visible){
	for(let label of allCss3DObjects){
		setLabelVisible(label,visible);
	}
}
//恢复默认显示状态
function setAllLabelDefaultVisibility(){
	for(let label of allCss3DObjects){
		setLabelVisible(label,label.defaultVisible);
	}
}
//根据零件名称获取label元素
// function getLabelByPartName(partname){
// 	var nodes = []
// 	for(let node of allCss3DObjects){
// 		if(node.name == partname + "_css"){
// 			nodes.push(node);
// 		}
// 	}
// 	return nodes;
// }

function addLabel(id,labelinfo,pos,offset){
    var node = new THREE.Object3D();
    //1 添加标签
    var eleWidth = 250;
    var eleHeight = 30+labelinfo.tips.length * 30;
	var scale = 0.2;
    var label = makeElementObject('div', eleWidth, eleHeight,scale);
    var htmlcontentStart = `
    <div class="card_item card_item_branch" id=${id}>
        <div class="card_item_bg card_item_bg_top"></div>
        <div class="card_item_bg card_item_bg_left"></div>
        <div class="card_item_bg card_item_bg_right"></div>
        `;
	var htmlcontentDynamic = "";
	//for(var i=0;i<labelinfo.tips.length;i++){
	//	var tip = labelinfo.tips[i];
	for(let tip of labelinfo.tips){
		var unit = tip.unit || "";
		htmlcontentDynamic += 
        `<ul class="data_list">
            <li class="data_list_item">
                <span class="data_name">${tip.name}：</span>
                <span class="data_v">-</span>
                <span class="data_unit">${unit}</span>
            </li>`
	}
    var htmlcontentEnd =         
        `</ul>
    </div>`;


	label.css3dObject.element.innerHTML = htmlcontentStart + htmlcontentDynamic + htmlcontentEnd;
    node.position.set(pos.x,pos.y,pos.z);
    node.add(label);
	label.scale.set(scale,scale,scale);
    label.position.set(offset.x,offset.y,offset.z);
    //1.1 计算最近的端点
    // var bbox = new THREE.Box3().setFromObject(label);
    // var boxsize = new THREE.Vector3();
    // bbox.getSize(boxsize);
    // var corners = [
    //     offset.clone().add(new THREE.Vector3(boxsize.x/2,0,0)),
    //     offset.clone().add(new THREE.Vector3(-boxsize.x/2,0,0)),
    //     offset.clone().add(new THREE.Vector3(0,boxsize.y/2,0)),
    //     offset.clone().add(new THREE.Vector3(0,-boxsize.y/2,0)),
    //     //offset.clone().add(new THREE.Vector3(0,0,boxsize.z/2)),
    //     //offset.clone().add(new THREE.Vector3(0,0,-boxsize.z/2)),
    // ];

    // var nearestPt = corners[0];
    // for(let v of corners){
    //     if(v.length() < nearestPt.length()){
    //         nearestPt = v;
    //     }
    // }
    // console.log("nearest point is ",nearestPt)

    var nearestPt = offset.clone();
    //2 添加线条
    const points = [];
    var segs = 80;
    var lenOff = nearestPt.length()/segs;
    for(var i=0;i<segs;i+=2){
        var part = i / segs;
        var partNext = (i+1)/segs;
        points.push( nearestPt.clone().multiplyScalar(part) );
        points.push( nearestPt.clone().multiplyScalar(partNext) );
    }

    //console.log(points)
    const geometry = new THREE.BufferGeometry().setFromPoints( points );

    const material = new THREE.LineBasicMaterial( { color: 0xffffff } );
    const line = new THREE.LineSegments( geometry, material );

    node.add(line);
	//属性设置
	node.defaultVisible = labelinfo.show;
	node.name = id + "_css";
	//记录:
	allCss3DObjects.push(node);

    return node;
}

function addSimpleLabel()
{
    var allinfo = {
        "partName": "4",
        "offset": {
            "x": 0,
            "y": 0,
            "z": 0
        },
        "tips": [
            {
                "name": "定子温度",
                "id": "710010102083171",
                "unit": "℃"
            }
        ],
        "show": true
    };

    return addLabel(addLabel.length+"",allinfo,new THREE.Vector3(0,0,0),new THREE.Vector3(100,100,100));
}

export{addSimpleLabel}